#include "py/builtin.h"
#include "py/runtime.h"
#include "py/obj.h"
#include "py/binary.h"
#include "moopi.h"
#include <string.h>

STATIC mp_obj_t moopi_label_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
    mp_arg_check_num(n_args, 0, 0 ,1, false);
    // 创建对象
    moopi_label_t *self = (moopi_label_t *)m_new_obj(moopi_label_t);
    // 设置对象实例类型
    self->base.base.type = &moopi_type_label;
    self->text = NULL;
    if(n_args==1 && mp_obj_get_type(args[0]) == &mp_type_str){
        const char *t = mp_obj_str_get_str(args[0]);
        size_t len = strlen(t)+1;
        self->text = m_malloc(len);
        if(self->text!=NULL){
            memcpy(self->text,t,len);
        }
    }
    // 返回对象
    return MP_OBJ_FROM_PTR(self);
}

/**
 * @brief 获取或设置字符
*/
STATIC mp_obj_t moopi_label_text(size_t n_args, const mp_obj_t *args){
    moopi_label_t *self = MP_OBJ_TO_PTR(args[0]);
    
    if(n_args>1){
        const char *t = mp_obj_str_get_str(args[1]);
        size_t len = strlen(t)+1;
        if(self->text!=NULL){
            m_free(self->text);
            self->text=NULL;
        }
        self->text = m_malloc(len);
        if(self->text!=NULL){
            memcpy(self->text,t,len);
        }
    }

    mp_obj_t text = mp_obj_new_str("",0);
    if(self->text !=NULL){
        text = mp_obj_new_str(self->text,strlen(self->text));
    }
    return MP_OBJ_FROM_PTR(text);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(moopi_label_text_obj,1,2,moopi_label_text);

/**
 * @brief 父类继承
*/
void call_parent_methods(mp_obj_t obj, qstr attr, mp_obj_t *dest)
{
    const mp_obj_type_t *type = mp_obj_get_type(obj);
    while (type->locals_dict != NULL)
    {
        mp_map_t *locals_map = &type->locals_dict->map;
        mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
        if (elem != NULL)
        {
            // 添加当前类自己的所有成员
            mp_convert_member_lookup(obj, type, elem->value, dest);
            break;
        }
        if (type->parent == NULL)
        {
            break;
        }
        // 递归搜索父类成员
        type = type->parent;
    }
}

// 定义类成员的全局字典
const mp_rom_map_elem_t moopi_label_local_dict_table[] = {
    {MP_ROM_QSTR(MP_QSTR_text), MP_ROM_PTR(&moopi_label_text_obj)},
};

// 将成员全局字典转换为 micropython 对象
STATIC MP_DEFINE_CONST_DICT(moopi_label_local_dict, moopi_label_local_dict_table);

// 定义类的类型结构
const mp_obj_type_t moopi_type_label = {
    {&mp_type_type},
    .name = MP_QSTR_Label,
    .locals_dict = (mp_obj_dict_t *)&moopi_label_local_dict,
    .make_new = moopi_label_make_new,
    .parent = &moopi_type_object,
    .attr = call_parent_methods
};